package com.yangchuang.openpicture.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yangchuang.openpicture.communication.ResultCode;
import com.yangchuang.openpicture.exception.BussinessException;
import com.yangchuang.openpicture.mapper.CategoryMapper;
import com.yangchuang.openpicture.pojo.Category;
import com.yangchuang.openpicture.service.CategoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 分类服务实现类
 *
 * @author naiyi
 * @since 2025-09-01
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    private final CategoryMapper categoryMapper;

    @Override
    public List<Category> getAllCategories() {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //根据id升序排序 1-2-3-...
        wrapper.orderByAsc(Category::getId);
        return categoryMapper.selectList(wrapper);
    }

    @Override
    public Long addCategory(String name) {
        // 检查分类名称是否已存在
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getName, name);
        Category existingCategory = categoryMapper.selectOne(wrapper);
        if (existingCategory != null) {
            throw new BussinessException(ResultCode.REPEATED_CATEGORY);
        }
        Category category = new Category();
        category.setName(name);
        // 保存分类
        categoryMapper.insert(category);
        return category.getId();
    }

}
